<template>
	<view class="count-box">
	    <button @tap="handleSub" class="minus" :disabled="value <= 1">-</button>
	    <input :value="value" @tap="handleChange" class="inp" type="text">
	    <button @tap="handleAdd" class="add">+</button>
	</view>
</template>

<script>

	export default {
		name: "CountBox",
		props: {
			value: {
			  type: Number,
			  default: 1
			}
		},
		methods: {
		    handleSub () {
				if (this.value <= 1) {
					return
				}
				const num = this.value - 1
				this.$emit('input', num)
		    },
		    handleAdd () {
				const num = this.value + 1
				this.$emit('input', num)
		    },
		    handleChange (e) {
				const num = +e.target.value // 转数字处理 (1) 数字 (2) NaN
				// 输入了不合法的文本 或 输入了负值，回退成原来的 value 值
				if (isNaN(num) || num < 1) {
					e.target.value = this.value
					return
				}
				this.$emit('input', num)
		    }
		}
	}
</script>

<style lang="less">
.count-box {
	width: 220rpx;
	display: flex;
	.add, .minus {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 60rpx;
		height: 60rpx;
		outline: none;
		border: none;
		background-color: #efefef;
	}
	.minus:disabled {
		color: #cdcdcd;
	}
	.inp {
		width: 80rpx;
		height: 60rpx;
		outline: none;
		border: none;
		margin: 0 10rpx;
		background-color: #efefef;
		text-align: center;
	}
}
</style>
